﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace MqttServerTest
{
    public static class ComputeFileSHA256
    {
        public static string ComputeFiel(string filepath)
        {
            //判断文件是否存在，如果不存在则抛出空异常
            if (File.Exists(filepath))
            {
                //初始化SHA256对象
                using (SHA256 sha256=SHA256.Create())
                {
                    try
                    {
                        //打开文件
                        FileStream fileStream = File.Open(filepath,FileMode.Open);
                        //确保位于流的开头
                        fileStream.Position = 0;
                        //计算SHA256
                        byte[] shaValue = sha256.ComputeHash(fileStream);
                        //关闭文件流
                        fileStream.Close();
                        //返回SHA256的值
                        return ByteArrToString(shaValue);
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }
            throw new ArgumentNullException(nameof(filepath));
        }

        public static string ByteArrToString(byte[] _byte)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var b in _byte)
            {
                stringBuilder.Append(string.Format("{0:x2}",b));
            }
            return stringBuilder.ToString();
        }
    }
}
